package com.andnnl.list;

import com.sun.media.sound.SoftTuning;

import java.awt.*;
import java.util.*;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by chenss on 2023/1/10.
 */
public class ListRemoveTest {

//    static List<Integer> list = new ArrayList<>();
    static List<Integer> list = new Vector<>();
    static ExecutorService addPool = Executors.newFixedThreadPool(100);
    static ExecutorService removePool = Executors.newFixedThreadPool(100);
    public static void main(String[] args) throws InterruptedException {
        test1();
        for (int i = 0; i < 10; i++) {
            Thread.sleep(1000);
            System.out.println(list.size());
        }
//        Collections.synchronizedList()
    }

    private static void test1() throws InterruptedException {
        for (int i = 0; i < 10000; i++) {
            int finalI = i;
            addPool.submit(()->{
                System.out.println("add "+finalI);
                list.add(finalI);
            });
        }
        Thread.sleep(2000);
        System.out.println("sleep");
        for (int i = 0; i < 10000; i++) {
            int finalI = i;
            removePool.submit(()->{
                remove(finalI);
            });
        }
//        for (int i = 0; i < 100000; i++) {
//            int finalI = i;
//            addPool.submit(()->{
//                System.out.println("add "+finalI);
//                list.add(finalI);
//            });
//        }
    }

    private synchronized static void remove(int finalI) {
        for (Iterator<Integer> iterator = list.iterator(); iterator.hasNext(); ) {
            Integer i =  iterator.next();
            if(i==finalI){
//                System.out.println("remove "+finalI);
                iterator.remove();
                return;
            }
        }
    }


//    private static void test1() {
//        for (int i = 0; i < 1000; i++) {
//            list.re(1);
//        }
//    }
}
